/**
 * 表单处理
 */
define(['jquery',
    'underscore',
    'FilterView',
    'text!templates/common/error_block.html'
],
    function ($, _, FilterView, errorBlock) {
        var formView = FilterView.extend({
            el: 'body',

            events: {
                'submit                          form[data-operation="ajax"]': 'submitAjaxForm',
                'submit                       form[data-operation="confirm"]': 'submitConfirmForm',
                'submit                       form[data-operation="operate"]': 'submitOperateForm',
            },

            initialize: function () {
                this.errorBlockTpl = _.template(errorBlock);
            },

            /**
             * 提交表单
             * @param event
             */
            submitAjaxForm: function (event) {
                event.preventDefault();
                var $target = this.$(event.target),
                    method = $target.attr('method') || 'post',
                    action = $target.attr('action') || '#',
                    successMode = $target.data('success-mode'),
                    errorMode = $target.data('error-mode'),
                    formData = this.serializeToJson($target),
                    that = this;

                $.ajax({
                    url: action,
                    type: method,
                    data: $.param(formData, true),
                    dataType: 'json',
                    beforeSend: function (req) {
                        req.setRequestHeader("Accept", "application/json");
                    },
                }).done(function (res, status, xhr) {
                    if (!res.success) {
                        that.handleError($target, errorMode, res, status, xhr)
                    } else {
                        that.handleSuccess($target, successMode, res, status, xhr)
                    }
                }).fail(function () {
                    that.errorAlert('网络连接超时');
                }).always(function () {
                    if (that.$('.validate-code').length > 0) {
                        that.refreshValidateCode();
                    }
                    $target.find(':submit').prop('disabled', false);
                });

                $target.find(':submit').prop('disabled', true);
            },

            /**
             * 提交confirm表单
             * @param event
             */
            submitConfirmForm: function (event) {
                event.preventDefault();
                var $form = $(event.target),
                    $ConfirmTarget = $($form.data('confirm-target')),
                    action = $form.attr('action') || '#',
                    method = $form.attr('method') || 'post',
                    successMode = $form.data('success-mode'),
                    errorMode = $form.data('error-mode'),
                    params = {},
                    that = this;

                $ConfirmTarget.find('.factor:checked').each(function () {
                    var key = $(this).attr('name');
                    if (!_.isArray(params[key])) {
                        params[key] = [];
                    }
                    params[key].push($(this).val());
                });

                $.ajax({
                    url: action,
                    type: method,
                    data: params,
                    dataType: 'json',
                    beforeSend: function (req) {
                        req.setRequestHeader("Accept", "application/json");
                    },
                }).done(function (res, status, xhr) {
                    if (res.Errors && !res.Errors.IsValid) {
                        that.handleError($form, errorMode, res, status, xhr)
                    } else {
                        that.handleSuccess($form, successMode, res, status, xhr)
                    }
                }).fail(function () {
                    that.errorAlert('网络连接超时');
                }).always(function () {
                    $form.find(':submit').prop('disabled', false);
                });
                $form.find(':submit').prop('disabled', true);
            },

            //# 将表单数据序列化为json
            //
            serializeToJson: function ($form) {
                var obj = {};
                var arry = $form.serializeArray();
                $.each(arry, function () {
                    if (obj[this.name] !== undefined) {
                        if (!obj[this.name].push) {
                            obj[this.name] = [obj[this.name]];
                        }
                        obj[this.name].push(this.value || '');
                    } else {
                        obj[this.name] = this.value || '';
                    }
                });
                return obj;
            },

            /**
             * 表单提交成功处理
             * @param $form 一个jquery表单对象
             * @param res 服务器响应数据
             * @param successMode 成功处理方式
             */
            handleSuccess: function ($form, successMode, res, status, xhr) {
                var that = this;
                //如果表单的父元素是一个模态框，在提交成功时先关闭模态框
                if ($form.closest('.modal').length > 0) {
                    that.destoryModal($form.closest('.modal'))
                }

                switch (successMode) {
                    case 'refresh':
                        $form[0].reset();
                        that.refresh($($form.data('refresh-target')), that.generateParams());
                        that.successAlert("操作成功");
                        break;
                    case 'reload':
                        window.location.reload();
                        that.successAlert("操作成功");
                        break;
                    case 'redirect':
                        window.location.href = xhr.getResponseHeader('Location');
                        break;
                    case 'deferRedirect':
                        that.successAlert("操作成功,3秒后跳转至新页面...");
                        setTimeout(function () {
                            window.location.href = xhr.getResponseHeader('Location');
                        }, 3000);
                        break;
                    case 'remotemodal':
                        that.getRemoteModal(xhr.getResponseHeader('Location'));
                        break;
                    case 'alert':
                        that.successAlert("操作成功");
                        break;
                    default:
                        that.successAlert("操作成功");
                }
            },

            /**
             * 表单提交失败处理
             * @param $form 一个jquery表单对象
             * @param res 服务器响应数据
             * @param errorMode 错误处理方式
             */
            handleError: function ($form, errorMode, res, status, xhr) {
                var that = this;
                switch (errorMode) {
                    case 'append':
                        $form.find('.error-block').remove();
                        $form.append(this.errorBlockTpl({
                            errorMessage: res.errors[0].message
                        }));
                        break;
                    case 'alert':
                        that.errorAlert(res.errors[0].message);
                        break;
                    default:
                        that.errorAlert(res.errors[0].message);
                }
            },

            //# 获取RmoteModal
            //
            getRemoteModal: function (url) {
                var $page = $('#Page'),
                    that = this;

                $.ajax({
                    url: url,
                    type: 'GET',
                    dataType: 'html',
                    beforeSend: function (req) {
                        req.setRequestHeader("Accept", "text/html");
                    },
                }).done(function (res) {
                    if ($('#RemoteModal').length > 0) {
                        $('.modal-backdrop').remove();
                        $('#RemoteModal').remove();
                    }
                    $page.append(res);
                    that.initDisplay();

                    var $RemoteModal = that.$('#RemoteModal'),
                        scriptPath = $RemoteModal.data('script-path') || 'ModalView';
                    $RemoteModal.modal('show');

                    require([scriptPath], function (View) {
                        that.remoteView = new View();
                    });
                }).always(function () {
                    $page.removeClass('loading');
                })
                $page.addClass('loading');
            },

        });
        return formView;
    });
